#include <allegro.h>
#include <stdio.h>
#include "race.h"


BITMAP* load_background_bmp(BITMAP *Background)
{
	Background=load_bitmap("race.bmp", NULL);
	if(Background == NULL){
		set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
		allegro_message("Unable to load image !\n%s\n", allegro_error);
		return (NULL);
	}
	
	return (Background);
}

void draw_background(BITMAP *Background,BITMAP * Buffer, int position)
{
	//blit(Background, Buffer, 0, 0, 0, 0, SCREEN_W, SCREEN_H);
	draw_sprite(Buffer, Background, position, 0);
}

void destroy_background(BITMAP * Background)
{
	destroy_bitmap(Background);
}

void load_cars(Car *car, Car *car_r)
{
	car->car = load_bitmap("car.bmp",NULL);
	car_r->car = load_bitmap("car1.bmp", NULL);
}

void destroy_cars(Car *car, Car *car_r)
{
	destroy_bitmap(car->car);
	destroy_bitmap(car_r->car);
}


void init_cars(Car *car, Car *car_r)
{
	car->x = 10;
	car->y = 315;
	car_r->x = 10;
	car_r->y = 225;
}

void move_background(BITMAP * Background, int *position, BITMAP *Buffer)
{
	/*if (*position==-5600)
		{
			*position=0;
        	}*/
	clear_bitmap(Buffer);
        draw_sprite(Buffer, Background, *position, 0);
        //blit(Background, Buffer, *position, 0, 0, 0, Background->w, Background->h);
        
	usleep(50000);
	if (*position > -5600)
		{
			*position-=20;
        	}
	//(*position)-=20;
	
}

void move_car(Car *car, int c1)
{
c1=0;

	if (key[KEY_RIGHT] && (car->x < SCREEN_W - car->car->w))
	{
			
		(car->x)+=2;
		c1++;
                
	}
	
	if (key[KEY_LEFT] && (car->x > 0))
	{
		(car->x)-=2;
	}
		
       	if (car->y!=315)
       	{
       		(car->y)+=40;
       	}
        
       	if (key[KEY_UP])
       	{
       		(car->y)-=40;
       	}
}

void move_car_random(Car *car_r, int c2)
{
c2=0;
	if(car_r->x < SCREEN_W - car_r->car->w)		
	{
		(car_r->x)++;
		c2++;
	}	
}

void move_cars(Car *car, Car *car_r,int position,BITMAP * Background, BITMAP *Buffer)
{
int c1, c2;	
	move_car(&(*car),c1);
	move_car_random(&(*car_r),c2);
}


void draw_cars(Car *car, Car *car_r,BITMAP *Buffer)
{
	draw_sprite(Buffer, car->car, car->x, car->y);
	draw_sprite(Buffer, car_r->car, car_r->x, car_r->y);
}

void win_lose(int c1, int c2, int position, BITMAP *Buffer)
{
BITMAP *win;
BITMAP *lose;
	win = load_bitmap("right3.bmp",NULL);
	lose = load_bitmap("left3.bmp",NULL);
	
if((position == -5600) && c1>c2)
{
	//textout_centre_ex(Buffer, font, "YOU WIN !!!", SCREEN_W / 2, SCREEN_H / 2, makecol(255, 255,0), -1);
	draw_sprite(Buffer, win, 300, 150);
}

if((position == -5600) && c1<c2)
{
	//textout_centre_ex(Buffer, font, "YOU LOSE !!!", SCREEN_W / 2, SCREEN_H / 2, makecol(255, 255, 0), -1);
	draw_sprite(Buffer, lose, 300, 150);
}
}
